package cn.iocoder.yudao.module.trade.service.price.calculator;


import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.module.promotion.api.quickcombination.QuickCombinationApi;
import cn.iocoder.yudao.module.promotion.api.quickcombination.dto.QuickCombinationProductRespDTO;
import cn.iocoder.yudao.module.promotion.enums.common.PromotionTypeEnum;
import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateReqBO;
import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateRespBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Order(TradePriceCalculator.ORDER_QUICK_COMBINATION_ACTIVITY)
@Slf4j
public class TradeQuickCombinationActivityPriceCalculator implements TradePriceCalculator{

    @Resource
    private QuickCombinationApi quickCombinationApi;

    @Override
    public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) {
        // 1. 判断订单类型和是否具有拼团活动编号
        if (param.getQuickCombinationActivityId() == null) {
            return;
        }

        Assert.isTrue(param.getItems().size() == 1, "促销互动，只允许选择一个商品");


        TradePriceCalculateRespBO.OrderItem orderItem = result.getItems().get(0);

        QuickCombinationProductRespDTO productRespDTO = quickCombinationApi.validateQuickCombination(param.getUserId(), param.getQuickCombinationActivityId(), orderItem.getSkuId(), orderItem.getCount());

        // 3.1 记录优惠明细
        Integer discountPrice = orderItem.getPayPrice() - productRespDTO.getCombinationPrice() * orderItem.getCount();
        TradePriceCalculatorHelper.addPromotion(result, orderItem,
                param.getCombinationActivityId(), "", PromotionTypeEnum.QUICK_COMBINATION_ACTIVITY.getType(),
                StrUtil.format("促销活动：省 {} 元", TradePriceCalculatorHelper.formatPrice(discountPrice)),
                discountPrice);
        // 3.2 更新 SKU 优惠金额
        orderItem.setDiscountPrice(orderItem.getDiscountPrice() + discountPrice);
        TradePriceCalculatorHelper.recountPayPrice(orderItem);
        TradePriceCalculatorHelper.recountAllPrice(result);
    }
}
